from playwright.sync_api import sync_playwright
import time
import random
from tools.Result import error_result, success_result
from service.SlidePositionService import get_gap_position
from tjyz_detail import get_html_detail


def perform_slide(page, max_retries=3):
    """执行滑块验证，支持自动重试"""
    retry_count = 0
    while retry_count < max_retries:
        try:
            # 计算缺口位置
            try:
                image_data = page.evaluate('''() => {  
                    const canvas = document.querySelector('canvas');  
                    return canvas.toDataURL('image/png').split(',')[1];  
                }''')

                gap_x = get_gap_position(image_data)

            except Exception as e:
                print(f"缺口检测失败，使用默认偏移量: {e}")
                gap_x = 50  # 备用值

            # 模拟拖动
            slider = page.query_selector(".slider")
            slider_bbox = slider.bounding_box()
            start_x = slider_bbox["x"] + slider_bbox["width"] / 2
            start_y = slider_bbox["y"] + slider_bbox["height"] / 2
            target_x = start_x + gap_x + 8

            page.mouse.move(start_x, start_y)

            page.mouse.down()
            steps = random.randint(15, 30)
            for i in range(steps):
                x = start_x + (target_x - start_x) * (i / steps)
                y = start_y + random.uniform(-2, 2)
                page.mouse.move(x, y)
                time.sleep(random.uniform(0.01, 0.02))

            page.mouse.up()

            # 检查成功
            if page.query_selector(".prompt-info.success"):

                return True
            else:
                retry_count += 1
                print(f"验证失败，第 {retry_count} 次重试...")
                time.sleep(0.5)

        except Exception as e:
            print(f"滑动过程中出错: {e}")
            retry_count += 1

    return False

def login_with_slide(
    username: str,
    password: str,
    login_url: str ,
    detail_url: str ,
    max_slide_retries: int = 3
) -> dict:
    """执行带滑块验证的登录，并返回登录接口的 JSON 数据"""
    with sync_playwright() as playwright:
        browser = playwright.webkit.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        page.set_default_timeout(5000)
        try:
            page.goto(login_url, wait_until="networkidle", timeout=15000)
            page.get_by_text("登录", exact=True).click()
            page.get_by_role("button", name="密码登录").click()
            page.get_by_role("textbox", name="手机号码").fill(username)
            page.get_by_role("textbox", name="密码").click()
            page.get_by_role("textbox", name="密码").fill(password)
            page.get_by_role("button", name="登录", exact=True).click()
            if not perform_slide(page, max_slide_retries):
                return error_result("滑块验证失败")

            # 等待登录接口响应
            page.wait_for_timeout(4000)  # 简单延迟，确保响应已捕获

            return get_html_detail(page,detail_url)

        except Exception as e:
            return  error_result("f登录异常: {}"+str(e))
        finally:
            page.close()
            context.close()
            browser.close()

def login_result(response: dict) -> dict:
    if response.get("result")==0:
        return success_result("成功",response.get("data",{}).get("userDetail"))
    return error_result("登录失败，接口信息异常")
if __name__ == "__main__":

        result = login_with_slide(
            username="13180093138",
            password="TJYZ@0n36c",
            login_url="https://www.crcccl.com/",
            detail_url="https://www.crcccl.com/#/auction/detail?biddingID=1965227695449051137",
        )
        print("最终结果:", result)